<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>人力资源管理系统 - 请假申请</title>
  <!-- 引入外部资源 -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

  <!-- Tailwind配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#2563eb',
            secondary: '#64748b',
            success: '#10b981',
            warning: '#f59e0b',
            danger: '#ef4444',
            dark: '#1e293b',
            light: '#f8fafc'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 引入公共CSS -->
  <link rel="stylesheet" href="css/common.css">

  <!-- 引入API和公共JS -->
  <script src="js/api.js"></script>
  <script src="js/common.js"></script>
</head>
<body class="bg-gray-50 text-gray-800 font-sans">
  <div id="app" class="flex h-screen overflow-hidden"></div>

  <script>
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      if (checkAuthentication()) {
        initPage();
      }
    });

    // 初始化页面
    function initPage() {
      // 加载侧边栏和用户信息
      initSidebar();
      initUserInfo();
      initLogout();

      // 加载请假申请页面
      loadLeaveRequestPage();
    }

    // 加载请假申请页面
    function loadLeaveRequestPage() {
      // 显示加载状态
      showLoading();

      // 获取用户信息
      const userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        const user = JSON.parse(userInfo);
        document.getElementById('app').innerHTML = `
          <!-- 侧边栏 -->
          <aside id="sidebar" class="w-64 bg-white border-r border-gray-200 flex-shrink-0 hidden md:block transition-all duration-300">
            <div class="p-5 border-b border-gray-200">
              <h1 class="text-xl font-bold text-primary">人力资源管理系统</h1>
            </div>

            <nav class="p-3">
              <ul></ul>
            </nav>

            <div class="absolute bottom-0 w-full p-4 border-t border-gray-200">
              <div class="flex items-center gap-3">
                <img id="userAvatar" src="${user.avatar || 'https://picsum.photos/200/200?random=1'}" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
                <div>
                  <p id="user" class="font-medium text-sm">${user.name || user.username}</p>
                  <p id="userRole" class="text-xs text-gray-500">${user.role || '普通用户'}</p>
                </div>
                <button id="logoutBtn" class="ml-auto text-gray-500 hover:text-danger">
                  <i class="fa fa-sign-out"></i>
                </button>
              </div>
            </div>
          </aside>

          <!-- 主内容区 -->
          <main class="flex-1 flex flex-col overflow-hidden">
            <!-- 顶部导航 -->
            <header class="bg-white border-b border-gray-200 h-16 flex items-center justify-between px-6">
              <div class="flex items-center">
                <button id="sidebarToggle" class="md:hidden mr-4 text-gray-500">
                  <i class="fa fa-bars text-xl"></i>
                </button>
                <h2 id="pageTitle" class="text-lg font-semibold">请假申请</h2>
              </div>

              <div class="flex items-center gap-4">
                <div class="relative">
                  <input type="text" placeholder="搜索..." id="globalSearch" class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary w-64">
                  <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                </div>

                <button id="notificationBtn" class="relative text-gray-500 hover:text-primary">
                  <i class="fa fa-bell text-xl"></i>
                  <span id="notificationCount" class="absolute -top-1 -right-1 bg-danger text-white text-xs w-4 h-4 rounded-full flex items-center justify-center">3</span>
                </button>
              </div>
            </header>

            <!-- 页面内容 -->
            <div class="flex-1 overflow-y-auto p-6">
              <div class="card mb-6">
                <h3 class="text-lg font-semibold p-4 border-b border-gray-100">提交请假申请</h3>
                <div class="p-4">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                      <label for="leaveType" class="block text-sm font-medium text-gray-700 mb-1">请假类型</label>
                      <select id="leaveType" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                        <option value="annual">年假</option>
                        <option value="sick">病假</option>
                        <option value="personal">事假</option>
                        <option value="other">其他</option>
                      </select>
                    </div>
                    <div>
                      <label for="startDate" class="block text-sm font-medium text-gray-700 mb-1">开始日期</label>
                      <input type="date" id="startDate" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                    <div>
                      <label for="endDate" class="block text-sm font-medium text-gray-700 mb-1">结束日期</label>
                      <input type="date" id="endDate" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                    <div>
                      <label for="leaveDays" class="block text-sm font-medium text-gray-700 mb-1">请假天数</label>
                      <input type="number" id="leaveDays" min="0.5" step="0.5" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                  </div>
                  <div class="mb-4">
                    <label for="reason" class="block text-sm font-medium text-gray-700 mb-1">请假原因</label>
                    <textarea id="reason" rows="3" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"></textarea>
                  </div>
                  <div class="flex justify-end gap-2">
                    <button class="btn btn-secondary" id="cancelBtn">取消</button>
                    <button class="btn btn-primary" id="submitBtn">提交申请</button>
                  </div>
                </div>
              </div>

              <div class="card">
                <h3 class="text-lg font-semibold p-4 border-b border-gray-100">请假历史</h3>
                <div class="overflow-x-auto">
                  <table class="w-full">
                    <thead>
                      <tr class="bg-gray-50 text-left">
                        <th class="px-4 py-3 text-sm font-medium text-gray-500">请假类型</th>
                        <th class="px-4 py-3 text-sm font-medium text-gray-500">开始日期</th>
                        <th class="px-4 py-3 text-sm font-medium text-gray-500">结束日期</th>
                        <th class="px-4 py-3 text-sm font-medium text-gray-500">天数</th>
                        <th class="px-4 py-3 text-sm font-medium text-gray-500">状态</th>
                        <th class="px-4 py-3 text-sm font-medium text-gray-500">操作</th>
                      </tr>
                    </thead>
                    <tbody id="leaveHistoryTableBody">
                      <!-- 请假历史数据将通过API加载 -->
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </main>
        `;

        // 确保DOM渲染完成后再初始化侧边栏和其他功能
        setTimeout(() => {
          // 重新初始化侧边栏
          initRoleBasedSidebar(user.role);
          // 初始化日期选择事件
          initDateSelection();
          // 初始化表单提交事件
          initFormSubmit();
          // 加载请假历史
          loadLeaveHistory();
          // 隐藏加载状态
          hideLoading();
        }, 0);
      } else {
        // 隐藏加载状态
        hideLoading();
        showToast('无法获取用户信息', 'error');
      }
    }

    // 加载请假历史
    function loadLeaveHistory() {
      // 显示加载状态
      showLoading();

      // 调用API获取请假历史
      api.getLeaveHistory()
        .then(leaveHistory => {
          // 隐藏加载状态
          hideLoading();
          // 渲染请假历史
          renderLeaveHistory(leaveHistory);
        })
        .catch(error => {
          // 隐藏加载状态
          hideLoading();
          console.error('获取请假历史失败:', error);
          showToast('获取请假历史失败，请稍后重试', 'error');
          // 在错误情况下，可以显示模拟数据
          renderLeaveHistory([
            { leaveType: 'annual', startDate: '2023-10-01', endDate: '2023-10-07', days: 5, status: 'approved', id: 1 },
            { leaveType: 'sick', startDate: '2023-11-15', endDate: '2023-11-16', days: 2, status: 'approved', id: 2 },
            { leaveType: 'personal', startDate: '2023-12-10', endDate: '2023-12-10', days: 1, status: 'pending', id: 3 }
          ]);
        });
    }

    // 渲染请假历史
    function renderLeaveHistory(leaveHistory) {
      const tableBody = document.getElementById('leaveHistoryTableBody');
      if (!tableBody) return;

      if (!leaveHistory || leaveHistory.length === 0) {
        tableBody.innerHTML = `
          <tr>
            <td colspan="6" class="px-4 py-6 text-center text-gray-500">暂无请假记录</td>
          </tr>
        `;
        return;
      }

      let html = '';
      leaveHistory.forEach(leave => {
        // 格式化请假类型显示
        const leaveTypeMap = {
          'annual': '年假',
          'sick': '病假',
          'personal': '事假',
          'other': '其他'
        };
        const displayLeaveType = leaveTypeMap[leave.leaveType] || leave.leaveType;

        // 格式化状态显示
        let statusHtml = '';
        switch (leave.status) {
          case 'approved':
            statusHtml = '<span class="badge bg-success/20 text-success">已批准</span>';
            break;
          case 'pending':
            statusHtml = '<span class="badge bg-warning/20 text-warning">审批中</span>';
            break;
          case 'rejected':
            statusHtml = '<span class="badge bg-danger/20 text-danger">已拒绝</span>';
            break;
          default:
            statusHtml = '<span class="badge bg-gray/20 text-gray">未知</span>';
        }

        html += `
          <tr class="border-b border-gray-100">
            <td class="px-4 py-3 text-sm">${displayLeaveType}</td>
            <td class="px-4 py-3 text-sm">${leave.startDate}</td>
            <td class="px-4 py-3 text-sm">${leave.endDate}</td>
            <td class="px-4 py-3 text-sm">${leave.days}</td>
            <td class="px-4 py-3 text-sm">${statusHtml}</td>
            <td class="px-4 py-3 text-sm"><button class="text-primary hover:underline" onclick="viewLeaveDetail(${leave.id})">查看</button></td>
          </tr>
        `;
      });

      tableBody.innerHTML = html;
    }

    // 查看请假详情
    function viewLeaveDetail(leaveId) {
      // 这里可以实现查看请假详情的逻辑
      showToast('查看请假详情功能待实现', 'info');
    }

    // 初始化日期选择事件
    function initDateSelection() {
      const startDateInput = document.getElementById('startDate');
      const endDateInput = document.getElementById('endDate');
      const leaveDaysInput = document.getElementById('leaveDays');

      if (startDateInput && endDateInput && leaveDaysInput) {
        const calculateLeaveDays = () => {
          const startDate = new Date(startDateInput.value);
          const endDate = new Date(endDateInput.value);

          if (!isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
            if (endDate >= startDate) {
              const timeDiff = endDate.getTime() - startDate.getTime();
              const dayDiff = timeDiff / (1000 * 3600 * 24) + 1; // 包含开始和结束日期
              leaveDaysInput.value = dayDiff;
            } else {
              showToast('结束日期不能早于开始日期', 'error');
              endDateInput.value = '';
              leaveDaysInput.value = '';
            }
          }
        };

        startDateInput.addEventListener('change', calculateLeaveDays);
        endDateInput.addEventListener('change', calculateLeaveDays);
      }
    }

    // 初始化表单提交事件
    function initFormSubmit() {
      const submitBtn = document.getElementById('submitBtn');
      const cancelBtn = document.getElementById('cancelBtn');

      if (submitBtn) {
        submitBtn.addEventListener('click', () => {
          const leaveType = document.getElementById('leaveType').value;
          const startDate = document.getElementById('startDate').value;
          const endDate = document.getElementById('endDate').value;
          const leaveDays = document.getElementById('leaveDays').value;
          const reason = document.getElementById('reason').value;

          // 表单验证
          if (!startDate || !endDate || !leaveDays || !reason) {
            showToast('请填写完整请假信息', 'error');
            return;
          }

          // 提交请假申请
          submitLeaveRequest({
            leaveType,
            startDate,
            endDate,
            days: parseFloat(leaveDays),
            reason
          });
        });
      }

      if (cancelBtn) {
        cancelBtn.addEventListener('click', () => {
          // 重置表单
          document.getElementById('leaveType').value = 'annual';
          document.getElementById('startDate').value = '';
          document.getElementById('endDate').value = '';
          document.getElementById('leaveDays').value = '';
          document.getElementById('reason').value = '';
        });
      }
    }

    // 提交请假申请
    function submitLeaveRequest(data) {
      // 显示加载状态
      showLoading();

      // 调用API提交请假申请
      api.submitLeaveRequest(data)
        .then(response => {
          // 隐藏加载状态
          hideLoading();

          // 显示成功提示
          showToast('请假申请提交成功', 'success');

          // 重置表单
          document.getElementById('leaveType').value = 'annual';
          document.getElementById('startDate').value = '';
          document.getElementById('endDate').value = '';
          document.getElementById('leaveDays').value = '';
          document.getElementById('reason').value = '';

          // 刷新请假历史
          loadLeaveHistory();
        })
        .catch(error => {
          // 隐藏加载状态
          hideLoading();
          console.error('提交请假申请失败:', error);
          showToast('提交请假申请失败，请稍后重试', 'error');
        });
    }
  </script>
</body>
</html>